package com.hornet.oauth.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hornet.commons.web.BaseController;
import com.hornet.commons.web.model.AjaxResponse;
import com.hornet.oauth.sdk.weibo.Users;
import com.hornet.oauth.sdk.weibo.model.User;
import com.hornet.oauth.sdk.weibo.model.WeiboException;

@Controller
@RequestMapping("/oauth/weibo")
public class WeiboLoginController extends BaseController {

	@RequestMapping(value = "login", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResponse sina_weibo_login(HttpServletRequest request, HttpSession session) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		try {
			System.out.println("使用微博登录....");
			
			com.hornet.oauth.sdk.weibo.Oauth oauth = new com.hornet.oauth.sdk.weibo.Oauth();
			String url = oauth.authorize("code") ;
			
			ajaxResponse.setMessage(url);
			System.out.println(url);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return ajaxResponse;
	}
	
	@RequestMapping(value = "callback", method = RequestMethod.GET)
	public String weibo_callback(@RequestParam String code) {
		try {
			System.out.println("微博验证回调....");
			System.out.println("code：" + code);

			com.hornet.oauth.sdk.weibo.Oauth oauth = new com.hornet.oauth.sdk.weibo.Oauth();
			com.hornet.oauth.sdk.weibo.http.AccessToken accessToken = oauth.getAccessTokenByCode(code);

			String uid = accessToken.getUid();
			Users users = new Users(accessToken.getAccessToken());
			User user = users.showUserById(uid);

			System.out.println(accessToken);

			String username = user.getScreenName(); // 用户呢称
			String avatar = user.getAvatarLarge(); // 用户头像
			String gender = user.getGender(); // 性别
			if ("m".equals(user.getGender())) {
				gender = "男";
			} else if ("f".equals(user.getGender())) {
				gender = "女";
			} else {
				gender = "未知";
			}

			System.out.println(username);
			System.out.println(avatar);
			System.out.println(gender);
			System.out.println();

		} catch (WeiboException e) {
			e.printStackTrace();
		}
		
		return "/oauth/weibo_callback" ;
	}
}
